package com.cwt_taxi_xa.protocol.can.manager;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.media.AudioManager;
import android.os.Handler;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;

import com.cwt_taxi_xa.ActivityConditioning;
import com.cwt_taxi_xa.constants.MyStatus;
import com.cwt_taxi_xa.constants.SPConstants;
import com.cwt_taxi_xa.custom_view.FloatAirCondition;
import com.cwt_taxi_xa.custom_view.FloatFuelAlarm;
import com.cwt_taxi_xa.protocol.MCUUtil;
import com.cwt_taxi_xa.protocol.can.IViewWindowManager;
import com.cwt_taxi_xa.util.AppLog;
import com.cwt_taxi_xa.util.SPUtils;
import com.cwt_taxi_xa.util.VolumeControl;

import java.lang.reflect.Field;

//import com.cwt_taxi_xa.R;


/**
 * https://github.com/leavesC/FloatBall
 * Created by ZY on 2016/8/10.
 * 管理者，单例模式
 */
public class ViewManager implements IViewWindowManager {
    static String TAG = "ViewManager";
    private FloatAirCondition mFloatAirCondition;

    private FloatFuelAlarm mFloatFuelAlarm;

    private WindowManager windowManager;

    private static ViewManager manager;

    private LayoutParams floatBallParams;

    private LayoutParams fuelAlarmParams;

    private Context context;

    private Handler mHandler = new Handler();

    private boolean ha;

    public static int lastvic = 6;
    public static boolean fuelAlarm = false;

    //启用焦点功能
    private boolean useAudioFocus = true;
    private int status = AudioManager.AUDIOFOCUS_REQUEST_FAILED;
    private AudioManager mAudioManager;


    //私有化构造函数
    public ViewManager(Context context) {
        this.context = context.getApplicationContext();
        init();
    }

    public void init() {

        mAudioManager = (AudioManager)context.getSystemService(Service.AUDIO_SERVICE);

        windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        mFloatFuelAlarm = new FloatFuelAlarm(context);
        mFloatAirCondition = new FloatAirCondition(context);
        MCUUtil.mConditioningDecode.register(mFloatAirCondition);
        MCUUtil.mConditioningDecode.register(this);
        View.OnTouchListener touchListener = new View.OnTouchListener() {
            float startX;
            float startY;
            float tempX;
            float tempY;

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        startX = event.getRawX();
                        startY = event.getRawY();

                        tempX = event.getRawX();
                        tempY = event.getRawY();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        float x = event.getRawX() - startX;
                        float y = event.getRawY() - startY;
                        // 计算偏移量，刷新视图
                        floatBallParams.x += x;
                        floatBallParams.y += y;
                        windowManager.updateViewLayout(mFloatAirCondition, floatBallParams);
                        startX = event.getRawX();
                        startY = event.getRawY();
                        break;
                    case MotionEvent.ACTION_UP:
                        // 判断松手时View的横坐标是靠近屏幕哪一侧，将View移动到依靠屏幕
                        float endX = event.getRawX();
                        float endY = event.getRawY();
                        if (endX < getScreenWidth() / 2) {
                            endX = 0;
                        } else {
                            endX = getScreenWidth() - mFloatAirCondition.width;
                        }
                        floatBallParams.x = (int) endX;
                        windowManager.updateViewLayout(mFloatAirCondition, floatBallParams);
                        // 如果初始落点与松手落点的坐标差值超过6个像素，则拦截该点击事件
                        // 否则继续传递，将事件交给OnClickListener函数处理
                        if (Math.abs(endX - tempX) > 6 && Math.abs(endY - tempY) > 6) {
                            return true;
                        }
                        break;
                }
                return false;
            }
        };
        View.OnClickListener clickListener = new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                if(context != null){
                    try {
                        Intent intent = new Intent(context,ActivityConditioning.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(intent);
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        };
        mFloatAirCondition.setOnTouchListener(touchListener);
        //mFloatAirCondition.setOnClickListener(clickListener);
    }

    //显示浮动小球
    public void showFloatBall() {
        if (floatBallParams == null && MCUUtil.mConditioningDecode.getPower() == 1) {
            floatBallParams = new LayoutParams();
            //mFloatAirCondition.
            floatBallParams.width = mFloatAirCondition.width;
            floatBallParams.height = mFloatAirCondition.height;
            floatBallParams.gravity = Gravity.TOP;
            //floatBallParams.gravity = Gravity.CENTER_HORIZONTAL;
            //floatBallParams.verticalMargin = 1;
            //floatBallParams.y =120;
            //floatBallParams.y = 20;
            //floatBallParams.width = 100;
            //floatBallParams.height = 300 - getStatusHeight();
            //floatBallParams.gravity = Gravity.CENTER_HORIZONTAL | Gravity.LEFT;
            //floatBallParams.x = 120;

            floatBallParams.type = LayoutParams.TYPE_SYSTEM_ALERT;
            //floatBallParams.type = LayoutParams.TYPE_SYSTEM_OVERLAY;
            //允许点击返回
            floatBallParams.flags = LayoutParams.FLAG_NOT_FOCUSABLE | LayoutParams.FLAG_NOT_TOUCH_MODAL | LayoutParams.FLAG_FULLSCREEN;
            floatBallParams.format = PixelFormat.RGBA_8888;
            windowManager.addView(mFloatAirCondition, floatBallParams);
        }
    }

    public void hiddenFloatBall(){
        if(floatBallParams != null){
            windowManager.removeView(mFloatAirCondition);
            floatBallParams = null;
        }
    }

    //获取ViewManager实例
    public static ViewManager getInstance(Context context) {
        if (manager == null) {
            manager = new ViewManager(context);
        }
        return manager;
    }

    //获取屏幕宽度
    public int getScreenWidth() {
        Point point = new Point();
        windowManager.getDefaultDisplay().getSize(point);
        return point.x;
    }

    //获取屏幕高度
    public int getScreenHeight() {
        Point point = new Point();
        windowManager.getDefaultDisplay().getSize(point);
        return point.y;
    }

    public void showFuelAlarm(){
        if (fuelAlarmParams == null && !MCUUtil.mConditioningDecode.isFuelAlarmInit() &&
            MCUUtil.mConditioningDecode.getFuelAlarm() == 1) {
            fuelAlarmParams = new LayoutParams();
            fuelAlarmParams.width = 900;
            fuelAlarmParams.height = 90;
            fuelAlarmParams.gravity = Gravity.CENTER;//| Gravity.TOP
            fuelAlarmParams.type = LayoutParams.TYPE_SYSTEM_ALERT;//LayoutParams.TYPE_SYSTEM_OVERLAY
            fuelAlarmParams.flags = LayoutParams.FLAG_NOT_FOCUSABLE | LayoutParams.FLAG_NOT_TOUCH_MODAL | LayoutParams.FLAG_FULLSCREEN;
            fuelAlarmParams.format = PixelFormat.RGBA_8888;
            windowManager.addView(mFloatFuelAlarm, fuelAlarmParams);
            MCUUtil.mConditioningDecode.setFuelAlarmInit(true);//警告只提示一次


            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        requestAudioFocus();
                        Thread.sleep(300);
                        fuelAlarmChannel();
                        Thread.sleep(500);
                        VolumeControl.playSound();
                        //MediaPlayer.create(MainApplication.getInstance(), R.raw.ding);
                        //Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
                        //Ringtone rt = RingtoneManager.getRingtone(MainApplication.getInstance(), uri);
                        //rt.play();

                        Thread.sleep(1500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    resetFuelAlarmChannel();
                }
            }).start();
//            mHandler.postDelayed(new Runnable() {
//                @Override
//                public void run() {
//                    resetFuelAlarmChannel();
//                }
//            },1500);
            removeDelayedFuelAlarm();
            delayedHiddenFuelAlarm();
        }
    }

    public void hiddenFuelAlarm(){
        if(fuelAlarmParams != null){
            windowManager.removeView(mFloatFuelAlarm);
            fuelAlarmParams = null;
        }
    }

    //获取状态栏高度
    public int getStatusHeight() {
        try {
            Class<?> c = Class.forName("com.android.internal.R$dimen");
            Object object = c.newInstance();
            Field field = c.getField("status_bar_height");
            int x = (Integer) field.get(object);
            return context.getResources().getDimensionPixelSize(x);
        } catch (Exception e) {
            return 0;
        }
    }

    @Override
    public void power(int type) {
        if(type == 1){
            showFloatBall();
        }else if(type == 2){
            hiddenFloatBall();
        }
     //0x00：无效
        // 0x01：打开
	 //0x02：关闭
	 //0x03：保留
    }

    @Override
    public void fuelAlarm(int alarm) {
        if(alarm ==1){
            showFuelAlarm();
            //removeDelayedFuelAlarm();
            //delayedHiddenFuelAlarm();
        }else{
            //removeDelayedFuelAlarm();
            //hiddenFuelAlarm();
        }
    }
    private Runnable hiddenRunnable = new Runnable() {
        @Override
        public void run() {
            hiddenFuelAlarm();
        }
    };

    private void delayedHiddenFuelAlarm(){
        mHandler.postDelayed(hiddenRunnable,8000);
    }

    private void removeDelayedFuelAlarm(){
        mHandler.removeCallbacks(hiddenRunnable);

    }

    public synchronized void fuelAlarmChannel() {
        AppLog.d(TAG, "fuelAlarmChannel vichl:" + MyStatus.vichl);
        lastvic = SPUtils.getParamInteger(SPConstants.SPK_vol, SPConstants.SPV_vol);
        if (MyStatus.vichl != 2) {
            MyStatus.lastvichl = MyStatus.vichl;
            MCUUtil.selecterVic(2);
            MCUUtil.setvol(25, "fuelAlarmChannel");
            MCUUtil.hasVic(true);
            fuelAlarm = true;
            AppLog.d(TAG, "speakIP lastvic:" + lastvic);
        }else{
            MCUUtil.setvol(25, "fuelAlarmChannel");
            MCUUtil.hasVic(true);
        }
    }

    public synchronized  void resetFuelAlarmChannel(){
        if(fuelAlarm){
            fuelAlarm = false;
            MCUUtil.selecterVic(MyStatus.lastvichl);
            MCUUtil.setvol(lastvic, "警告结束恢复音量");
            AppLog.d(TAG,"警告结束恢复音量");
        }else{
            MCUUtil.setvol(lastvic, "fuelAlarmChannel");
        }
        abandonAudioFocus();
    }


    private void requestAudioFocus() {
        status = mAudioManager.requestAudioFocus(audioFocusChangeListener,AudioManager.STREAM_MUSIC,AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
    }

    private void abandonAudioFocus(){
        mAudioManager.abandonAudioFocus(audioFocusChangeListener);
    }

    AudioManager.OnAudioFocusChangeListener audioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() {
        @Override
        public void onAudioFocusChange(int focusChange) {
        }
    };
}
